import {
    getBreadCrumbList,
    setTagNavListInLocalstorage,
    getMenuByRouter,
    getTagNavListFromLocalstorage,
    getHomeRoute,
    getNextRoute,
    routeHasExist,
    routeEqual,
    getRouteTitleHandled,
    localSave,
    localRead,

} from '@/libs/util'
import {
    saveErrorLogger,
    getCascade,
    getDepartment
} from '@/api/data'
import router from '@/router'
import routers from '@/router/routers'
import config from '@/config'
const {
    homeName
} = config

const closePage = (state, route) => {
    const nextRoute = getNextRoute(state.tagNavList, route)
    state.tagNavList = state.tagNavList.filter(item => {
        return !routeEqual(item, route)
    })
    router.push(nextRoute)
}

export default {
    state: {
        breadCrumbList: [],
        tagNavList: [],
        homeRoute: {},
        local: localRead('local'),
        errorList: [],
        hasReadErrorPage: false,
        // 分部列表
        branchList: [],
        // 缓存的页面
        catchPages: [],
        // 公共部门
        department: []
    },
    getters: {
        menuList: (state, getters, rootState) => getMenuByRouter(routers, rootState.user.access),
        errorCount: state => state.errorList.length,
        // 获取分部列表
        getBranchList: state => state.branchList,
        // 获取缓存页面
        getCatchPages: state => state.catchPages,
        // 获取公共部门
        getDem: state => state.department
    },
    mutations: {
        // 设置公共部门
        setDepartment(state, department) {
            state.department = department
        },
        addCatchPages(state, item) {
            if (state.catchPages.indexOf(item) === -1)
                state.catchPages.push(item);
        },
        removeCatchPages(state, item) {
            if (item == 'all') {
                state.catchPages = []
                return false
            }
            let index = state.catchPages.indexOf(item);
            if (index >= 0)
                state.catchPages.splice(index, 1)
        },

        // 设置分部列表
        setBranchList(state, branchList) {
            state.branchList = branchList
        },

        setBreadCrumb(state, route) {
            state.breadCrumbList = getBreadCrumbList(route, state.homeRoute)
        },
        setHomeRoute(state, routes) {
            state.homeRoute = getHomeRoute(routes, homeName)
        },
        setTagNavList(state, list) {
            // console.log('list:+++++++', list);
            let tagList = []
            if (list) {
                tagList = [...list]
            } else tagList = getTagNavListFromLocalstorage() || []
            if (tagList[0] && tagList[0].name !== homeName) tagList.shift()
            let homeTagIndex = tagList.findIndex(item => item.name === homeName)
            if (homeTagIndex > 0) {
                let homeTag = tagList.splice(homeTagIndex, 1)[0]
                tagList.unshift(homeTag)
            }
            state.tagNavList = tagList
            setTagNavListInLocalstorage([...tagList])
        },
        closeTag(state, route) {
            let tag = state.tagNavList.filter(item => routeEqual(item, route))
            route = tag[0] ? tag[0] : null
            if (!route) return
            closePage(state, route)
        },
        myClose(state, name) {

            if (!name) return
            let routeArr = state.tagNavList
            routeArr.forEach(item => {
                if (item.name == name) {
                    closePage(state, item)
                }
            })
        },

        addTag(state, {
            route,
            type = 'unshift'
        }) {
            let router = getRouteTitleHandled(route)
            if (!routeHasExist(state.tagNavList, router)) {
                if (type === 'push') state.tagNavList.push(router)
                else {
                    if (router.name === homeName) state.tagNavList.unshift(router)
                    else state.tagNavList.splice(1, 0, router)
                }
                setTagNavListInLocalstorage([...state.tagNavList])
            }
        },
        setLocal(state, lang) {
            localSave('local', lang)
            state.local = lang
        },
        addError(state, error) {
            state.errorList.push(error)
        },
        setHasReadErrorLoggerStatus(state, status = true) {
            state.hasReadErrorPage = status
        }
    },
    actions: {
        addErrorLog({
            commit,
            rootState
        }, info) {
            if (!window.location.href.includes('error_logger_page')) commit('setHasReadErrorLoggerStatus', false)
            const {
                user: {
                    token,
                    userId,
                    userName
                }
            } = rootState
            let data = {
                ...info,
                time: Date.parse(new Date()),
                token,
                userId,
                userName
            }
            saveErrorLogger(info).then(() => {
                commit('addError', data)
            })
        },
        // 获取分部级联
        getBranchCascade({
            commit
        }) {
            getCascade().then(res => {
                if (res.data.code === 1) {
                    let branchList = JSON.parse(JSON.stringify(res.data.data.list))
                    commit('setBranchList', branchList)
                } else {
                    this.$Notice.error({
                        title: res.data.msg,
                        duration: 3
                    })
                }


            })
        },
        // 获取公共部门
        getDepartmentByAction({
            commit
        }) {
            getDepartment().then(res => {
                if (res.data.code === 1) {
                    let dem = JSON.parse(JSON.stringify(res.data.data.list))
                    commit('setDepartment', dem)
                } else {
                    this.$Notice.error({
                        title: res.data.msg,
                        duration: 3
                    })
                }


            })
        }
    }
}